<template>
  <px-dialog v-model="visible" width="80%" :title="title" @close="cancel">
    <div class="flex-center table-top">
      <px-form ref="formRef" :model="queryParams" :inline="true" class="custom-form-ui search-form">
        <!-- <px-form-item v-if="fromPage === 'pressure'" label="时间粒度" prop="type">
          <px-select v-model="queryParams.type" placeholder="请选择时间粒度" @change="changeDateType">
            <px-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item> -->
        <px-form-item
          v-if="(queryParams.type === 'day' && fromPage === 'pressure') || fromPage === 'flowMeter'"
          label="日期"
          prop="date"
          style="width: 450px"
        >
          <px-date-picker
            v-model="queryParams.date"
            :clearable="false"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </px-form-item>
        <px-form-item v-if="queryParams.type === 'hour' && fromPage === 'pressure'" label="日期" prop="date" style="width: 450px">
          <px-date-picker
            v-model="queryParams.date"
            :clearable="false"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:00:00"
            value-format="YYYY-MM-DD HH:00:00"
          />
        </px-form-item>
        <px-form-item v-if="queryParams.type === 'minutes' && fromPage === 'pressure'" label="日期" prop="date" style="width: 450px">
          <px-date-picker
            v-model="queryParams.date"
            :clearable="false"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
          />
        </px-form-item>
        <div class="search-form-btn">
          <px-button type="primary" @click="handleQuery">查询</px-button>
          <px-button @click="resetQuery">重置</px-button>
          <px-button type="primary" plain @click="handleAssociateQuery">关联查询</px-button>
        </div>
      </px-form>
    </div>

    <!-- 曲线查看和关联查询 -->
    <!-- <div v-if="!isAssociate" v-loading="loading" class="content">
      <div ref="chartRef" class="chart-container" />
    </div>
    <div v-else v-loading="loading" class="associate-content">
      <div v-for="(item, index) in associateDataList" :key="item.itemKey" class="associate-container">
        <div :id="`chart${index}`" class="associate-chart-container" />
      </div>
    </div> -->
    <!-- 新接口的曲线查看和关联查询 -->
    <div v-if="!isAssociate" v-loading="loading" class="content">
      <div ref="newChartRef" class="chart-container" />
    </div>
    <div v-else v-loading="loading" class="associate-content">
      <div ref="newAssociateChartRef" class="chart-container" />
    </div>
  </px-dialog>
</template>

<script setup>
import { ref, reactive, nextTick, toRefs, computed, onMounted } from "vue";
import * as echarts from "echarts";
import { getPressureLineAPI, getFlowMeterLineAPI, getAssociationAPI } from "@/api/consumption/bulkGas";
import { queryScadaIndicator } from "@/api/machineApi";
import dayjs from "dayjs";
import { PxMessage } from "px-ui";
import { formatMissingData } from "@/utils/common";

const emits = defineEmits(["update:visible"]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  fromPage: {
    type: String,
    default: ""
  },
  data: {
    type: Object,
    default() {
      return {};
    }
  }
});
const title = "曲线查看" + "-" + props?.data?.gasName;

const visible = computed({
  get: () => props.visible,
  set: val => emits("update:visible", val)
});

const formRef = ref(null);
const chartRef = ref(null);
const newChartRef = ref(null);
const newAssociateChartRef = ref(null);

const defaultDateTime = [dayjs().subtract(24, "hour").format("YYYY-MM-DD HH:mm:ss"), dayjs().format("YYYY-MM-DD HH:mm:ss")];

const state = reactive({
  loading: false,
  typeList: [
    {
      label: "天",
      value: "day"
    },
    {
      label: "时",
      value: "hour"
    },
    {
      label: "分",
      value: "minutes"
    }
  ],
  queryParams: {
    // type: "day",
    type: "minutes",
    date: defaultDateTime
  },
  isAssociate: false, // 是否是关联查询
  associateDataList: []
});
const { loading, typeList, queryParams, isAssociate, associateDataList } = toRefs(state);

onMounted(() => {
  handleQuery();
});

const shortcuts = [
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 7);
      return [start, end];
    }
  }
];

const cancel = () => {
  emits("update:visible", false);
};

const changeDateType = () => {
  state.queryParams.date = "";
};

// 新接口的折现图
const getNewLineData = async () => {
  try {
    state.loading = true;
    // let startTime = state.queryParams.date ? `${state.queryParams.date[0]} 00:00:00` : dayjs().subtract(7, "day").format("YYYY-MM-DD") + ` 00:00:00`;
    // let endTime = state.queryParams.date ? `${state.queryParams.date[1]} 23:59:59` : dayjs().subtract(1, "day").format("YYYY-MM-DD") + ` 23:59:59`;

    // const startTime = dayjs().subtract(24, "hour").format("YYYY-MM-DD HH:mm:ss");
    // const endTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
    const res = await queryScadaIndicator({
      contentType: "LIST",
      bucketWidth: 1,
      bucketUnit: state.queryParams.type,
      point: [props.data.currentPoint],
      scale: "0.2",
      indicators: ["AVG"],
      // startTime: "2024-12-16 00:00:00",
      // endTime: "2024-12-19 23:59:59",
      startTime: state.queryParams.date[0],
      endTime: state.queryParams.date[1],
      pageNum: 0,
      pageSize: 0
    });
    if (res && res.rows) {
      newDrawChart(res, newChartRef.value);
    }
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

const getLineData = async () => {
  try {
    state.loading = true;
    let params = {};
    if (props.fromPage === "pressure") {
      params = {
        itemKey: props.data.itemKey,
        startTime:
          state.queryParams.date === "" ? "" : state.queryParams.type === "day" ? `${state.queryParams.date[0]} 00:00:00` : state.queryParams.date[0],
        endTime:
          state.queryParams.date === "" ? "" : state.queryParams.type === "day" ? `${state.queryParams.date[1]} 23:59:59` : state.queryParams.date[1],
        timePeriod: state.queryParams.type
      };
    } else {
      params = {
        itemKey: props.data.itemKey,
        startDate: state.queryParams.date === "" ? "" : state.queryParams.date[0],
        endDate: state.queryParams.date === "" ? "" : state.queryParams.date[1]
      };
    }

    // const res = props.fromPage === "pressure" ? await getPressureLineAPI(params) : await getFlowMeterLineAPI(params);
    // 之前是压力表和流量计用这个组件，处理接口不同，页面的样式做了调整
    const res = await getFlowMeterLineAPI(params);
    if (res && res.valueList) {
      drawChart(res, chartRef.value);
    }
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};

const drawChart = (data, dom) => {
  let myChart = echarts.init(dom);
  const min = value => {
    if (value.min < 0) {
      return Math.round(value.min * 1.5);
    } else {
      return 0;
    }
  };
  const max = value => {
    return Math.round(value.max * 1.5);
  };
  let option = {
    title: {
      text: data.itemName
    },
    tooltip: {
      // show: true,
      trigger: "axis",
      // axisPointer: { type: "shadow" },
      formatter: params => {
        const { seriesName, name, value } = params;
        const arr = params.map(item => {
          const { seriesName, value } = item;
          return `${seriesName}：${value?.toFixed(2)}`;
        });
        arr.unshift(params[0]?.axisValue);
        return arr.join("<br/>");
      }
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      show: true,
      type: "category",
      data: data.valueList.map(v => v.name)
    },
    yAxis: {
      show: true,
      type: "value",
      name: data.unit,
      min,
      max
    },
    series: [
      {
        data: formatMissingData(data.valueList.map(v => v.num)),
        type: "line"
      }
    ]
  };
  nextTick(() => {
    myChart.setOption(option);
  });
};

// 新接口的折线图
const newDrawChart = (data, dom) => {
  let type = state.queryParams.type;
  let myChart = echarts.init(dom);
  // 辅助线
  let markLineAry = [
    {
      yAxis: props?.data.lslValue || 0,
      lineStyle: {
        color: "red",
        type: "dashed"
      },
      label: {
        position: "end",
        formatter: `SPEC L: ${props?.data.lslValue}`
      }
    },
    {
      yAxis: props?.data.uslValue || 0,
      lineStyle: {
        color: "red",
        type: "dashed"
      },
      label: {
        position: "end",
        formatter: `SPEC U: ${props?.data.uslValue}`
      }
    }
  ];
  // 辅助线
  let markLineData = [];
  [props?.data.lslValue, props?.data.uslValue].forEach((i, idx) => {
    if (i) {
      markLineData.push(markLineAry[idx]);
    }
  });

  // y轴数据
  let seriesData = formatMissingData(data.rows.map(v => v.avg_value));
  // 最大的数值
  // let max = Math.max(...seriesData, props?.data.uslValue);
  // let mix = Math.min(...seriesData, props?.data.lslValue);
  const min = value => {
    if (value.min < 0) {
      return Math.round(value.min * 1.5);
    } else {
      return 0;
    }
  };
  const max = value => {
    return Math.round(value.max * 1.5);
  };
  let option = {
    grid: {
      // bottom: 140
      left: 90,
      right: 80,
      top: 50,
      bottom: 80
    },
    tooltip: {
      // show: true,
      trigger: "axis",
      // axisPointer: { type: "shadow" },
      formatter: params => {
        const { name, value } = params[0];
        return `${name}：${value?.toFixed(2)}`;
      }
    },

    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      show: true,
      type: "category",
      // data: data.rows.map(v => v[type]?.split(" ")[0]),
      data: data.rows.map(v => v[type]),
      axisLabel: {
        // interval: 0
        // rotate: 45
      }
    },
    yAxis: {
      type: "value",
      name: "",
      min,
      max,
      axisLine: {
        show: true, // 显示 Y 轴轴线
        lineStyle: {
          width: 1, // 轴线宽度
          type: "solid" // 轴线样式，可选值：'solid'（实线）、'dashed'（虚线）、'dotted'（点线）
        }
      }
    },
    dataZoom: [
      {
        type: "slider",
        orient: "vertical",
        filterMode: "none",
        left: 0,
        start: 0,
        end: 100
      },
      {
        type: "inside",
        orient: "vertical",
        filterMode: "none",
        start: 0,
        end: 100
      },
      {
        type: "slider",
        orient: "horizontal",
        filterMode: "none",
        start: 0,
        end: 100
      },
      {
        type: "inside",
        orient: "horizontal",
        filterMode: "none",
        start: 0,
        end: 100
      }
    ],
    series: [
      {
        data: seriesData,
        type: "line",
        markLine: {
          symbol: ["none", "none"],
          data: markLineData
        }
      }
    ]
  };
  nextTick(() => {
    myChart.setOption(option);
  });
};

// 关联查询
const getAssociateData = async () => {
  try {
    state.loading = true;
    const params = {
      gasName: props.data.gasName,
      startTime: state.queryParams.date === "" ? "" : `${state.queryParams.date[0]} 00:00:00`,
      endTime: state.queryParams.date === "" ? "" : `${state.queryParams.date[1]} 23:59:59`
    };
    const res = await getAssociationAPI(params);
    state.associateDataList = res;
    res.map((item, index) => {
      nextTick(() => {
        drawChart(item, document.getElementById(`chart${index}`));
      });
    });
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};

// 新的关联查询
const getNewAssociateData = async () => {
  try {
    state.loading = true;
    // let startTime = state.queryParams.date ? `${state.queryParams.date[0]} 00:00:00` : dayjs().subtract(7, "day").format("YYYY-MM-DD") + ` 00:00:00`;
    // let endTime = state.queryParams.date ? `${state.queryParams.date[1]} 23:59:59` : dayjs().subtract(1, "day").format("YYYY-MM-DD") + ` 23:59:59`;
    let pointAry = props.data.relationPoints?.map(item => item?.code);
    const res = await queryScadaIndicator({
      contentType: "LIST",
      bucketWidth: 1,
      bucketUnit: state.queryParams.type,
      point: pointAry,
      scale: "0.2",
      indicators: ["AVG"],
      // startTime: "2024-12-16 00:00:00",
      // endTime: "2024-12-19 23:59:59",
      startTime: state.queryParams.date[0],
      endTime: state.queryParams.date[1],
      pageNum: 0,
      pageSize: 0
    });
    if (res && res.rows) {
      newAssociateDrawChart(res, newAssociateChartRef.value);
    }
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

// 新的关联查询折线图
const newAssociateDrawChart = (data, dom) => {
  let type = state.queryParams.type;
  let myChart = echarts.init(dom);
  let pointAry = props.data.relationPoints?.map(item => item?.code);
  let seriesAry = [
    {
      name: "流量",
      data: [],
      type: "line",
      yAxisIndex: 0
    },
    {
      name: "压力",
      data: [],
      type: "line",
      yAxisIndex: 1
    },
    {
      name: "温度",
      data: [],
      type: "line",
      yAxisIndex: 2
    }
  ].slice(0, pointAry?.length);
  // 展示的数据
  data?.rows?.forEach(i => {
    pointAry.forEach((j, idx) => {
      if (i.point === j) {
        seriesAry[idx]?.data?.push(i.avg_value);
      }
    });
  });
  seriesAry = seriesAry.map(item => {
    item.data = formatMissingData(item.data);
    return item;
  });

  const min = value => {
    if (value.min < 0) {
      return Math.round(value.min * 1.5);
    } else {
      return 0;
    }
  };
  const max = value => {
    return Math.round(value.max * 1.5);
  };
  // y轴数据
  let yAxisAry = [
    {
      show: true,
      type: "value",
      name: "流量(NM^3)",
      min,
      max,
      axisLine: {
        show: true, // 显示 Y 轴轴线
        lineStyle: {
          width: 1, // 轴线宽度
          type: "solid" // 轴线样式，可选值：'solid'（实线）、'dashed'（虚线）、'dotted'（点线）
        }
      }
    },
    {
      show: true,
      type: "value",
      name: "压力",
      min,
      max,
      axisLine: {
        show: true, // 显示 Y 轴轴线
        lineStyle: {
          width: 1, // 轴线宽度
          type: "solid" // 轴线样式，可选值：'solid'（实线）、'dashed'（虚线）、'dotted'（点线）
        }
      }
    },
    {
      show: true,
      type: "value",
      name: "温度（℃）",
      min,
      max,
      position: "right",
      offset: 80,
      axisLine: {
        show: true, // 显示 Y 轴轴线
        lineStyle: {
          width: 1, // 轴线宽度
          type: "solid" // 轴线样式，可选值：'solid'（实线）、'dashed'（虚线）、'dotted'（点线）
        }
      }
    }
  ].slice(0, pointAry?.length);
  // x轴数据
  // let xAry = data.rows.map(v => v[type]?.split(" ")[0]) || [];
  let xAry = data.rows.map(v => v[type]) || [];
  const xAxisData = [...new Set(xAry)];
  let option = {
    title: {
      text: "关联查询"
    },
    grid: {
      // bottom: 140
      left: 90,
      right: pointAry?.length > 2 ? 160 : 80,
      top: 60,
      bottom: 80
    },
    tooltip: {
      // show: true,
      trigger: "axis",
      // axisPointer: { type: "shadow" },
      formatter: params => {
        const { seriesName, name, value } = params;
        const arr = params.map(item => {
          const { seriesName, value } = item;
          return `${seriesName}：${value?.toFixed(2)}`;
        });
        arr.unshift(params[0]?.axisValue);
        return arr.join("<br/>");
      }
    },

    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      show: true,
      type: "category",
      data: xAxisData,
      axisLabel: {
        // interval: 0,
        // rotate: 45
      }
    },
    yAxis: yAxisAry,
    dataZoom: [
      {
        type: "slider",
        orient: "vertical",
        filterMode: "none",
        left: 0,
        start: 0,
        end: 100
      },
      {
        type: "inside",
        orient: "vertical",
        filterMode: "none",
        start: 0,
        end: 100
      },
      {
        type: "slider",
        orient: "horizontal",
        filterMode: "none",
        start: 0,
        end: 100
      },
      {
        type: "inside",
        orient: "horizontal",
        filterMode: "none",
        start: 0,
        end: 100
      }
    ],
    series: seriesAry
  };
  nextTick(() => {
    myChart.setOption(option);
  });
};

// 查询
const handleQuery = () => {
  state.isAssociate = false;
  getNewLineData();
  // getLineData();
};

// 关联查询
const handleAssociateQuery = () => {
  state.isAssociate = true;
  // getAssociateData();
  getNewAssociateData();
};

// 重置
const resetQuery = () => {
  formRef.value.resetFields();
  state.queryParams = {
    // type: "day",
    // date: ""
    type: "minutes",
    date: defaultDateTime
  };
  handleQuery();
};

const handleDateChange = dateRange => {
  if (dateRange && dateRange.length === 2) {
    const [startDate, endDate] = dateRange;
    let startTime = new Date(startDate);
    let endTime = new Date(endDate);
    const diffInDays = Math.floor((endTime - startTime) / (1000 * 60 * 60 * 24));

    if (diffInDays > 6) {
      PxMessage.error("最大范围选择一周");
      state.queryParams.date = [];
    }
  }
};
</script>

<style lang="scss" scoped>
@import url("@/views/gas/consumption/scss/common.scss");

.content {
  width: 100%;
  height: 550px;
}

.associate-content {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  height: 550px;
}

.chart-container {
  width: 100%;
  height: 100%;
}

// .associate-container {
//   width: 480px;
//   height: 200px;
//   margin: 0 16px 16px 0;
//   border: 1px solid rgb(24 24 24 / 15%);
// }

// .associate-chart-container {
//   width: 100%;
//   height: 100%;
// }
</style>
